package com.yy.filter;

import com.alibaba.fastjson2.JSON;
import com.yy.constant.AuthConstant;
import com.yy.model.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 描述  解析token并告诉security这个用户的登录信息和权限信息
 * 作者 yy
 */
@Component
public class TokenTranslateFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 解析token
     * 我只将有token的请求 转换出来
     * 没有token的请求 不处理 交给框架来处理  如果框架配置了这个api的放行 则直接访问
     * 如果框架没有放行这个api 走框架的authenticationEntryPoint 返回401
     * 1.拿token值
     * 2.如果有 做转换（加一个续约的动作 ）
     * 3.放在security的上下文中去 （@PreAuthority('')）
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //得到前端传来authorization
        String authorization = request.getHeader(AuthConstant.AUTHORIZATION);
        //判断
        if (StringUtils.hasText(authorization)) {
            //取出token
            String token = authorization.replaceFirst(AuthConstant.BEARER, "");
            if (StringUtils.hasText(token)) {
                // 判断续约
                Long expire = stringRedisTemplate.getExpire(AuthConstant.LOGIN_TOKEN_PREFIX + token, TimeUnit.SECONDS);
                if(expire<=AuthConstant.TOKEN_EXPIRE_THRESHOLD_TIME){
                    stringRedisTemplate.expire(AuthConstant.LOGIN_TOKEN_PREFIX + token,AuthConstant.TOKEN_TIME,TimeUnit.SECONDS);
                }
                //从redis里面取出用户信息
                String json = stringRedisTemplate.opsForValue().get(AuthConstant.LOGIN_TOKEN_PREFIX + token);
                if (StringUtils.hasText(json)) {
                    SecurityUser securityUser= JSON.parseObject(json, SecurityUser.class);
                    //取出权限
                    Set<String> perms = securityUser.getPerms();
                    //告诉seucurity这个用户已登录
//                    List<SimpleGrantedAuthority> authorities=new ArrayList<>();
//                    for (String perm : perms) {
//                        authorities.add(new SimpleGrantedAuthority(perm));
//                    }
                    List<SimpleGrantedAuthority> authorities = perms.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
                    UsernamePasswordAuthenticationToken auth=new UsernamePasswordAuthenticationToken(securityUser,null,authorities);
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
            }
        }
        filterChain.doFilter(request,response);
    }
}
